package com.dayatang.android.Activity;

import java.util.Calendar;
import java.util.List;
import java.util.concurrent.ExecutionException;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.dayatang.android.Db.DictionaryServiceDb;
import com.dayatang.android.Model.Dictionary;
import com.dayatang.android.config.Config;

public class WorkLoadReportActivity extends BaseActivity {
	
	private final static int StartDATE_DIALOG = 0;
	private final static int EndDATE_DIALOG = 1;
	
	private String[] specialty;
	private String[] specialtyid;
	private Calendar c = null;
	
	private TextView startDateTextView,endDateTextView,specificationTextView,workloadReportNumTextView,workloadReportGeneralWorkdaysTextView,workloadReportMechanicWorkdaysTextView,workloadReportOutputValueTextView;
	private Spinner spinner;
	private Button submitBtn;
	
	private String workitemid;
	
	private String startDate,endDate,specification,workloadReportNum,workloadReportGeneralWorkdays,workloadReportMechanicWorkdays,workloadReportOutputValue;
	private ArrayAdapter<CharSequence> adapter;
	
	private DictionaryServiceDb dictionaryServiceDb;
	
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.workload_report_activity);
		
		dictionaryServiceDb = new DictionaryServiceDb(this);
		InitSprinnerData();
	}
	
	private void InitSprinnerData() {
		
		List<Dictionary> dictionaries = dictionaryServiceDb.getDictionaryByDictionaryType("workitem");
		if (dictionaries.size() > 0) {
			specialty = new String[dictionaries.size()];
			specialtyid = new String[dictionaries.size()];
			int i = 0;
			for (Dictionary dictionary : dictionaries) {
				specialty[i] = dictionary.getName();
				specialtyid[i] = dictionary.getThisid();
				i++;
			}
		} else {
			getDataByNetwork();
		}
		TextViewInit();
	}
	
	private void getDataByNetwork() {
		try {
			String url = getServerAddress() + "/remote/init-datas.action";
			String data = getHttpData(this, url);
			
			if (data != null) {
				JSONArray jsonArray = new JSONArray(data);
				specialty = new String[jsonArray.length()];
				specialtyid = new String[jsonArray.length()];
				
				for (int i = 0; i < jsonArray.length(); i++) {
					JSONObject jsonObject = jsonArray.getJSONObject(i);
					Dictionary dictionary = new Dictionary();
					dictionary.setName(jsonObject.getString("name"));
					dictionary.setThisid(jsonObject.getString("id"));
					dictionary.setType("workitem");
					dictionaryServiceDb.save(dictionary);
					specialty[i] = dictionary.getName();
					specialtyid[i] = dictionary.getThisid();
				}
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (ExecutionException e) {
			e.printStackTrace();
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}
	
	private void WorkLoadReportSubmit() {
		submitBtn = (Button) findViewById(R.id.workload_report_submit_btn);
		submitBtn.setOnClickListener(new View.OnClickListener() {
			public void onClick(View arg0) {
				SubmitWorkload();
			}
		});
	}
	
	private String getSubProejctId() {
		return getIntent().getStringExtra(Config.SUBPROJID);
	}
	
	private void SubmitWorkload() {
		if (checking()) {
			try {
				String url = getServerAddress() + "/remote/workload-report.action?subProjectId=" + getSubProejctId() + "&startDate=" + startDate + "&endDate=" + endDate + "&workItemId=" + workitemid + "&model=" + specification + "&quantity=" + workloadReportNum + "&generalWorkerWorkday=" + workloadReportGeneralWorkdays + "&technicianWorkday=" + workloadReportMechanicWorkdays + "&outputValue=" + workloadReportOutputValue;
				if (getHttpData(this, url) != null) {
					Toast.makeText(this,getString(R.string.report_success), Toast.LENGTH_LONG).show();  
					startActivity(new Intent(this,WorkLoadReportActivity.class));
					finish();
				}
			} catch (InterruptedException e) {
				e.printStackTrace();
			} catch (ExecutionException e) {
				e.printStackTrace();
			}
		}
	}
	
	private boolean checking() {
		GetTextViewValue();
		if (specification.equals("") || workloadReportNum.equals("") || workloadReportGeneralWorkdays.equals("") || workloadReportMechanicWorkdays.equals("") || workloadReportOutputValue.equals("") || startDate.equals("") || endDate.equals("") ){
			ToastShow(getString(R.string.report_alert_info));
			return false;
		} else {
			return true;
		}
	}
	
	private void GetTextViewValue() {
		startDateTextView = (TextView) findViewById(R.id.workload_startDate_editText);
		endDateTextView = (TextView) findViewById(R.id.workload_endDate_editText);
		
		specificationTextView = (TextView) findViewById(R.id.specification_editText);
		workloadReportNumTextView = (TextView) findViewById(R.id.workload_report_num_editText);
		workloadReportGeneralWorkdaysTextView = (TextView) findViewById(R.id.workload_report_general_workdays_editText);
		workloadReportMechanicWorkdaysTextView = (TextView) findViewById(R.id.workload_report_mechanic_workdays_editText);
		workloadReportOutputValueTextView = (TextView) findViewById(R.id.workload_report_outputValue_editText);
		
		specification = specificationTextView.getText().toString();
		workloadReportNum = workloadReportNumTextView.getText().toString();
		workloadReportGeneralWorkdays = workloadReportGeneralWorkdaysTextView.getText().toString();
		workloadReportMechanicWorkdays = workloadReportMechanicWorkdaysTextView.getText().toString();
		workloadReportOutputValue = workloadReportOutputValueTextView.getText().toString();
		
		startDate = startDateTextView.getText().toString();
		endDate = endDateTextView.getText().toString();
	}
	
	private void InitSpinner() {
		adapter = new ArrayAdapter<CharSequence>(this, android.R.layout.simple_spinner_item,specialty);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); 
		
		spinner = (Spinner) findViewById(R.id.project_installation_spinner);
		spinner.setAdapter(adapter);
		
		spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
			public void onItemSelected(AdapterView<?> parent, View view,   
                    int position, long id) {   
				spinner.getSelectedItem().toString();
				workitemid = specialtyid[position];
			}

			public void onNothingSelected(AdapterView<?> arg0) {
				
			}
		});
		WorkLoadReportSubmit();
	}
	
	private void TextViewInit() {
		
		startDateTextView = (TextView) findViewById(R.id.workload_startDate_editText);
		endDateTextView = (TextView) findViewById(R.id.workload_endDate_editText);
		
		startDateTextView.setOnTouchListener(new TextView.OnTouchListener() {
			public boolean onTouch(View v, MotionEvent event) {
				showDialog(StartDATE_DIALOG);
				return false;
			}
		});
		
		endDateTextView.setOnTouchListener(new TextView.OnTouchListener() {
			public boolean onTouch(View v, MotionEvent event) {
				showDialog(EndDATE_DIALOG);
				return false;
			}
		});
		
		InitSpinner();
	}
	
	protected Dialog onCreateDialog(int id) {
		
		Dialog dialog = null;
		
		switch (id) {
		
			case StartDATE_DIALOG:
				c = Calendar.getInstance();
				dialog = new DatePickerDialog(this, 
						new DatePickerDialog.OnDateSetListener() {
							public void onDateSet(DatePicker view, int year, int monthOfYear,
									int dayOfMonth) {
								
									startDateTextView.setText(year + "-" + (monthOfYear+1) + "-" + dayOfMonth);
							}
						}, 
					c.get(Calendar.YEAR), 
					c.get(Calendar.MONTH), 
					c.get(Calendar.DAY_OF_MONTH)
				);
				break;
			
			case EndDATE_DIALOG:
				c = Calendar.getInstance();
				dialog = new DatePickerDialog(this, 
						new DatePickerDialog.OnDateSetListener() {
							public void onDateSet(DatePicker view, int year, int monthOfYear,
									int dayOfMonth) {
								
									endDateTextView.setText(year + "-" + (monthOfYear+1) + "-" + dayOfMonth);
							}
						}, 
					c.get(Calendar.YEAR), 
					c.get(Calendar.MONTH), 
					c.get(Calendar.DAY_OF_MONTH)
				);
				break;
				
		}
		return dialog;
	}
	
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			this.finish();
			overridePendingTransition(R.anim.push_right_out, R.anim.push_right_in);
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(0,INIT_DATA_ID,0,getString(R.string.omenu_update_init_data));
		return true;
	}
	
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
			case INIT_DATA_ID:
				dictionaryServiceDb.delDictionaryByType(new String[]{"workitem"});
				getDataByNetwork();
				startActivity(new Intent(this,WorkLoadReportActivity.class));
				finish();
				return true;
		}
		return super.onOptionsItemSelected(item);
	}
	
}
